package com.bdzt.beidoubox.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.bdzt.beidoubox.R;
import com.bdzt.beidoubox.utils.L;
import com.bdzt.beidoubox.utils.T;

import java.math.BigDecimal;

/**
 * 指南针
 */
public class CompassActivity extends BaseActivity implements SensorEventListener {
    private TextView tv_data;
    private ImageView iv_needleBack;
    //传感器管理器
    private SensorManager mSensorManager;
    //恒定加速度传感器
    private Sensor mAccelerometer;
    //磁场传感器
    private Sensor mMagneticField;
    //传感器事件监听
    private LocationManager mLocationManager;
    private String mLocationProvider;// 位置提供者名称，GPS设备还是网络

    private float[] mAccelerometerValues = new float[3];
    private float[] mMagneticFieldValues = new float[3];
    private float[] mValues = new float[3];
    private float[] mMatrix = new float[9];
    private float mCurrentDegree = 0f;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);

        mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        initView();
    }

    private void initView() {
        iv_needleBack= (ImageView) findViewById(R.id.iv_needleBack);
        tv_data= (TextView) findViewById(R.id.tv_data);

        findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerService();
        registerService();

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregister();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregister();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                mAccelerometerValues = sensorEvent.values;
            }
            if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                mMagneticFieldValues = sensorEvent.values;
            }

            //调用getRotaionMatrix获得变换矩阵mMatrix[]
            SensorManager.getRotationMatrix(mMatrix, null, mAccelerometerValues, mMagneticFieldValues);
            SensorManager.getOrientation(mMatrix, mValues);
            //经过SensorManager.getOrientation(R, values);得到的values值为弧度
            //values[0]  ：azimuth 方向角，但用（磁场+加速度）得到的数据范围是（-180～180）,也就是说，0表示正北，90表示正东，180/-180表示正南，-90表示正西。
            // 而直接通过方向感应器数据范围是（0～359）360/0表示正北，90表示正东，180表示正南，270表示正西。
            float degree = (float) Math.toDegrees(mValues[0]);
            changeOrientation(degree);
            RotateAnimation ra = new RotateAnimation(mCurrentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

            ra.setDuration(500);
            ra.setFillAfter(true);
            iv_needleBack.startAnimation(ra);

            mCurrentDegree = -degree;
        }


    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    private void registerService() {
        registerSensorService();

    }

    private void registerSensorService() {
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL);
    }
    private void changeOrientation(float degree) {
        int temp = 0;
        String bearing="";
        if (degree>=0){
            temp=(int)degree;
        }else {
            temp=(int)360+(int)degree;
        }
        //方位
        if (temp <= 10 || temp >= 350) {
            bearing = "N" + temp + "°";
        } else if (temp <= 80) {
            bearing = "EN" + temp + "°";
        } else if (temp <= 100) {
            bearing = "E" + temp + "°";
        } else if (temp <= 170) {
            bearing = "ES" + temp + "°";
        } else if (temp <= 190) {
            bearing = "S" + temp + "°";
        } else if (temp <= 260) {
            bearing = "WS" + temp + "°";
        } else if (temp <= 280) {
            bearing = "W" + temp + "°";
        } else if (temp <= 350) {
            bearing = "WN" + temp + "°";
        }
        tv_data.setText(bearing);
    }

    private void unregister() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }

    }

}
